<template>
  <div class="news-list-page">
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <van-dropdown-menu>
        <van-dropdown-item
          v-model="selectedCategory"
          :options="categoryOptions"
          @change="handleCategoryChange"
        />
        <van-dropdown-item
          v-model="selectedSort"
          :options="sortOptions"
          @change="handleSortChange"
        />
      </van-dropdown-menu>
    </div>

    <!-- 新闻列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div
          v-for="item in newsList"
          :key="item.newsId || item.id"
          class="news-item"
          @click="goToDetail(item.newsId || item.id)"
        >
          <div class="news-content">
            <h3 class="news-title">{{ item.title }}</h3>
            <p class="news-summary">{{
              item.contentPreview ||
              (item.contentText ? item.contentText.substring(0, 100) + '...' : '无内容摘要')
            }}</p>
            <div class="news-meta">
              <span class="category">{{ item.category }}</span>
              <span class="time">{{ formatTime(item.pubTime || item.publishTime) }}</span>
              <span v-if="item.section" class="section">{{ item.section }}</span>
            </div>
          </div>
          <div v-if="item.image || item.imageUrl" class="news-image">
            <van-image
              :src="item.image || item.imageUrl"
              width="100"
              height="80"
              fit="cover"
              radius="8"
              :lazy-load="true"
            />
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 回到顶部 -->
    <van-back-top />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  DropdownMenu,
  DropdownItem,
  PullRefresh,
  List,
  Image,
  BackTop,
  Toast,
  showFailToast,
  showSuccessToast
} from 'vant'
import { articleApi } from '../utils/api'
import { formatTime } from '../utils/dateUtils'

const router = useRouter()
const route = useRoute()

// 响应式数据
const newsList = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const selectedCategory = ref(0)
const selectedSort = ref(0)
const categories = ref([])
const error = ref(null)

// 分页参数
const pageSize = ref(10)
const currentPage = ref(1)
const totalPages = ref(0)

// 筛选选项
const categoryOptions = computed(() => {
  const options = [{ text: '全部分类', value: 0 }]
  categories.value.forEach((category, index) => {
    options.push({ text: category, value: index + 1 })
  })
  return options
})

const sortOptions = [
  { text: '最新发布', value: 0 },
  { text: '最多阅读', value: 1 },
  { text: '最多收藏', value: 2 }
]

// 时间格式化函数已移至 @/utils/dateUtils.js

// 处理分页数据的通用函数
const handlePaginationData = (result) => {
  if (!result) {
    console.warn('API返回空数据')
    return false
  }

  // 情况1: 标准分页响应格式 {code: 200, data: {list: [...], pageNum: 1, pages: 5}}
  if (result.code === 200 && result.data && result.data.list) {
    const { list, pageNum, pages } = result.data
    if (currentPage.value === 1) {
      newsList.value = list
    } else {
      newsList.value.push(...list)
    }
    currentPage.value = pageNum
    totalPages.value = pages
    finished.value = pageNum >= pages
    return true
  }

  // 情况2: 直接返回分页数据 {list: [...], pageNum: 1, pages: 5}
  if (result.list && Array.isArray(result.list)) {
    const { list, pageNum, pages } = result
    if (currentPage.value === 1) {
      newsList.value = list
    } else {
      newsList.value.push(...list)
    }
    currentPage.value = pageNum || currentPage.value
    totalPages.value = pages || 1
    finished.value = (pageNum || currentPage.value) >= (pages || 1)
    return true
  }

  // 情况3: 直接返回数组
  if (Array.isArray(result)) {
    if (currentPage.value === 1) {
      newsList.value = result
    } else {
      newsList.value.push(...result)
    }
    // 如果返回的数据少于页面大小，说明已经到最后一页
    finished.value = result.length < pageSize.value
    return true
  }

  // 情况4: 未知格式
  console.warn('Unexpected response format:', result)
  return false
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const result = await articleApi.getAllCategories()
    if (result && Array.isArray(result)) {
      categories.value = result
    } else if (result && result.data && Array.isArray(result.data)) {
      categories.value = result.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    // 使用默认分类
    categories.value = ['校园新闻', '学术活动', '招生信息', '就业指导', '社团活动']
  }
}

// 加载新闻数据
const loadNews = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      currentPage.value = 1
      newsList.value = []
      finished.value = false
    }

    error.value = null

    // 构建请求参数
    const params = {
      limit: pageSize.value,
      page: currentPage.value
    }

    // 根据选择的分类添加筛选条件
    if (selectedCategory.value > 0 && categories.value.length > 0) {
      const categoryName = categories.value[selectedCategory.value - 1]
      const result = await articleApi.getArticlesByCategory(
        categoryName,
        currentPage.value,
        pageSize.value
      )

      if (!handlePaginationData(result)) {
        error.value = '获取文章列表失败'
      }
    } else {
      // 获取所有文章
      const result = await articleApi.getArticleList(params)

      if (!handlePaginationData(result)) {
        error.value = '获取文章列表失败'
      }
    }

    // 如果不是刷新，增加页码
    if (!isRefresh) {
      currentPage.value++
    }

  } catch (error) {
    console.error('加载新闻失败:', error)
    error.value = '加载失败，请检查网络连接'
    showFailToast('加载失败，请重试')
  }
}

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true
  await loadNews(true)
  refreshing.value = false
  showSuccessToast('刷新成功')
}

// 上拉加载
const onLoad = async () => {
  if (finished.value) return
  
  loading.value = true
  await loadNews()
  loading.value = false
}

// 处理分类变化
const handleCategoryChange = () => {
  onRefresh()
}

// 处理排序变化
const handleSortChange = () => {
  onRefresh()
}

// 跳转到详情页
const goToDetail = (newsId) => {
  router.push({ name: 'news-detail', params: { id: newsId } })
}

// 页面加载时获取数据
onMounted(async () => {
  // 先获取分类列表
  await fetchCategories()
  // 再获取新闻列表
  await loadNews(true)
})
</script>

<style scoped>
.news-list-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.filter-bar {
  background: white;
  border-bottom: 1px solid #ebedf0;
}

.news-item {
  display: flex;
  background: white;
  padding: 16px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.news-item:active {
  background-color: #f7f8fa;
}

.news-content {
  flex: 1;
  margin-right: 12px;
}

.news-title {
  font-size: 16px;
  font-weight: 600;
  line-height: 1.4;
  color: #323233;
  margin: 0 0 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-summary {
  font-size: 14px;
  color: #646566;
  line-height: 1.4;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
}

.category {
  color: #1989fa;
  background: #e8f3ff;
  padding: 2px 6px;
  border-radius: 10px;
}

.time {
  color: #969799;
}

.views {
  color: #969799;
}

.news-image {
  flex-shrink: 0;
}

/* 自定义下拉菜单样式 */
:deep(.van-dropdown-menu__bar) {
  height: 48px;
}

:deep(.van-dropdown-menu__item) {
  flex: 1;
}
</style>
